/*
    axios相关配置 拦截器
*/
import axios from 'axios';
import { get ,post } from './tools';
import * as config from './config';
import { Modal} from 'antd';
import * as Constant from '../common/const';


export const login = (data) => post({url: config.LOGIN,data:data})

export const logout = () => get({url: config.LOGOUT})


const info = Modal.info;
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if(config.method == 'get' && 
        ((config.url.indexOf('page') !== -1) || (config.url.indexOf('permission/get/all') !== -1))
    ){
        let comma = '&';
        (config.url.indexOf('permission/get/all') !== -1) &&  (comma = '?');
        config.url += `${comma}time=${new Date().getTime()}`;
    }
    return config;
}, function (error) {

    // 对请求错误做些什么
    return Promise.reject(error);
});

let infoNum = 0;//用于防止弹出多个提示会话超时的窗口的判断
axios.interceptors.response.use(function (response) {
    const data = response.data;
    if(Constant.REQUEST_UNAUTHORIZED == data.code && infoNum == 0 && !localStorage.getItem('logout')){ //会话过期，返回登录页面
        localStorage.removeItem('user');
        info({
            title:"系统提示",
            content:'会话已过期，请重新登录',
            maskClosable: true,
            onOk(){
                let href = window.location.href;
                href = href.substring(0,href.lastIndexOf('#')+1);
                window.location.href = `${href}/login`;
                infoNum --;
            },
        });
        infoNum ++ ;
    }
    localStorage.setItem('last',`${new Date().getTime()} `);
    return response;
}, function (error) {
    return Promise.reject(error);
});